package com.alibaba.csp.sentinel.dashboard.rule.redis;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.csp.sentinel.dashboard.rule.AbstractDynamicRuleProviderAndPublisher;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.csp.sentinel.util.StringUtil;

import io.lettuce.core.RedisClient;
import io.lettuce.core.api.sync.RedisCommands;
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
import io.lettuce.core.pubsub.api.sync.RedisPubSubCommands;

/**
* @Description: TODO
* @author blueice
* @date 2021年3月25日 下午2:42:55
*
*/
public abstract class AbstractRedisRuleProviderAndPublisher<T> extends AbstractDynamicRuleProviderAndPublisher<T>
{
    @Autowired
    private RedisClient redisClient;

    @Override
    public List<T> getRules(String appName) throws Exception {
        if (this.redisClient == null) {
            throw new IllegalStateException("Redis client has not been initialized or error occurred");
        }
        RedisCommands<String, String> stringRedisCommands = redisClient.connect().sync();
        String rules = stringRedisCommands.get(appName+ruleSuffix());
        if (StringUtil.isEmpty(rules)) {
            return new ArrayList<>();
        }
        return super.decoder.convert(rules);
    }
    
    @Override
    public void publish(String app, List<T> rules) throws Exception {
        AssertUtil.notEmpty(app, "app name cannot be empty");
        if (rules == null) {
            return;
        }
        
        StatefulRedisPubSubConnection<String, String> connection = redisClient.connectPubSub();
        RedisPubSubCommands<String, String> subCommands = connection.sync();
        String value = super.encoder.convert(rules);
        subCommands.multi();
        subCommands.set(app+ ruleSuffix(), value);
        subCommands.publish(app+ruleSuffix(), value);
        
        boolean isRollBack = subCommands.exec().wasRolledBack();
        
        if(isRollBack){
            throw new RuntimeException("publish to redis fail,redis Transaction roll back");
        }
    }
}
